package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;

    @Value("${out_put_path}")
    private String outPutPath;//从属性文件中读取要生成的html对应的目录

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();


        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> query = setmealDao.query(queryString);
        long total = query.getTotal();
        List<Setmeal> result = query.getResult();
        PageResult pageResult = new PageResult(total, result);

        return pageResult;
    }

    @Override
    public void delByid(Integer id) {
        //先删除关联表数据
        setmealDao.deleteAssociation(id);
        setmealDao.delById(id);
    }

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {

        setmealDao.add(setmeal);
        this.setCheckGroupAndSetmeal(setmeal.getId(), checkgroupIds);

        //将图片名称保存到Redis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());

        //生成静态页面
        generateMobileStaticHtml();
    }

    private void generateMobileStaticHtml() {
        List<Setmeal> list = setmealDao.findAll();
        //套餐
        generateMobileSetmealListHtml(list);
        //套餐详情
        generateMobileSetmealDetailHtml(list);

    }

    private void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList", list);
        generteHtml("mobile_setmeal.ftl", "m_setmeal.ftl", map);
    }

    private void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            HashMap<String, Object> map = new HashMap<>();
            Setmeal info = setmealDao.findById(setmeal.getId());
            map.put("setmeal", info);
            generteHtml("mobile_setmeal_detail.ftl", "m_setmeal_detail_" + setmeal.getId() + ".ftl", map);
        }

    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            File docFile = new File(outPutPath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            //输出文件
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.deleteAssociation(setmeal.getId());
        this.setCheckGroupAndSetmeal(setmeal.getId(), checkgroupIds);
        setmealDao.edit(setmeal);
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer id) {
        List<Integer> checkGroupIdsBySetmealId = setmealDao.findCheckGroupIdsBySetmealId(id);
        return checkGroupIdsBySetmealId;
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        List<Map<String, Object>> setmealList = setmealDao.findSetmealCount();
        return setmealList;
    }

    private void setCheckGroupAndSetmeal(Integer id, Integer[] checkgroupIds) {
        if (id != null && checkgroupIds.length > 0) {
            for (Integer i : checkgroupIds) {
                Map<String, Integer> mp = new HashMap<>();
                mp.put("setmealId", id);
                mp.put("checkgroupId", i);
                setmealDao.setCheckGroupAndSetmeal(mp);
            }

        }
    }
}
